<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-divider type="vertical" class="antd-modal-divider" />
        <h4 class="hClass">基本信息</h4>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-item label="标物名称" v-bind="validateInfos.name">
            <j-select-input v-model:value="formData.name" :showSearch="true" :options="nameOptions"
              :disabled="disabled" />
              <!-- <a-input v-model:value="formData.name" :disabled="disabled"></a-input> -->
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="标物类别" v-bind="validateInfos.type">
            <j-select-input v-model:value="formData.type" :showSearch="true" :options="typeOptions"
              :disabled="disabled" />
              <!-- <a-input v-model:value="formData.type" :disabled="disabled"></a-input> -->
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="标物批号" v-bind="validateInfos.batch">
            <a-input v-model:value="formData.batch" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="纯度/标准" v-bind="validateInfos.purity">
            <a-input v-model:value="formData.purity" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="生产厂家" v-bind="validateInfos.factory">
            <j-select-input v-model:value="formData.factory" :showSearch="true" :options="factoryOptions"
              :disabled="disabled" />
              <!-- <a-input v-model:value="formData.factory" :disabled="disabled"></a-input> -->
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="规格" v-bind="validateInfos.specs">
            <a-input v-model:value="formData.specs" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="入库数量" v-bind="validateInfos.number">
            <a-input-number v-model:value="formData.number" style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="单位" v-bind="validateInfos.units">
            <j-dict-select-tag v-model:value="formData.units" dictCode="units" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="有效期" v-bind="validateInfos.restrictedDate">
            <a-date-picker v-model:value="formData.restrictedDate" value-format="YYYY-MM-DD" style="width: 100%"
              :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="证书" v-bind="validateInfos.certificate">
            <j-upload v-model:value="formData.certificate" :disabled="disabled"></j-upload>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-divider type="vertical" class="antd-modal-divider" />
        <h4 class="hClass">外观及包装</h4>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-item label="颜色性状" v-bind="validateInfos.properties">
            <j-dict-select-tag v-model:value="formData.properties" dictCode="character" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="标识标签" v-bind="validateInfos.tag">
            <j-dict-select-tag v-model:value="formData.tag" dictCode="appearance" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="包装" v-bind="validateInfos.packages">
            <j-dict-select-tag v-model:value="formData.packages" dictCode="appearance" :disabled="disabled" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-divider type="vertical" class="antd-modal-divider" />
        <h4 class="hClass">其他</h4>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-item label="存放地点" v-bind="validateInfos.storagePlace">
            <a-input v-model:value="formData.storagePlace" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="购买日期" v-bind="validateInfos.buyDate">
            <a-date-picker placeholder="请选择购买日期" v-model:value="formData.buyDate" value-format="YYYY-MM-DD"
              style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="标物状态" v-bind="validateInfos.status">
            <j-dict-select-tag v-model:value="formData.status" dictCode="chemical_status" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="用途" v-bind="validateInfos.purpose">
            <a-textarea v-model:value="formData.purpose" rows="4" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="备注" v-bind="validateInfos.remark">
            <a-textarea v-model:value="formData.remark" rows="4" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="实物图片" v-bind="validateInfos.picture">
            <j-image-upload v-model:value="formData.picture" :disabled="disabled"></j-image-upload>
          </a-form-item>
        </a-col>
      </a-row>
      <!-- v-show控制子表是否显示 -->
      <div v-show="disabled">
        <a-tabs style="margin-bottom: 3px;">
          <a-tab-pane tab="物质领用记录">
            <div style="margin-bottom: 3px;">
              <a-row type="flex" style="margin-bottom: 3px;">
                <a-col :span="3" style="text-align: center;">物质名称</a-col>
                <a-col :span="3" style="text-align: center;">物质批号</a-col>
                <a-col :span="3" style="text-align: center;">领用时间</a-col>
                <a-col :span="3" style="text-align: center;">领用数量</a-col>
                <a-col :span="3" style="text-align: center;">领用人</a-col>
                <a-col :span="3" style="text-align: center;">归还时间</a-col>
                <a-col :span="3" style="text-align: center;">归还数量</a-col>
                <a-col :span="3" style="text-align: center;">归还人</a-col>
              </a-row>
              <!-- 下面是遍历放入表数据 -->
              <a-row type="flex" style="margin-bottom: 3px;height: 30px;" gutter="1px"
                v-for="( item, index ) in  chemicalUsed " :key="index">
                <a-col :span="2" style="display: none">
                  <a-form-item>
                    <a-input placeholder="id" v-model:value="item.id" />
                  </a-form-item>
                </a-col>
                <a-col :span="3">
                  <a-form-item>
                    <a-input v-model:value="item.name" style="width: 130px;" :disabled="true" />
                  </a-form-item>
                </a-col>
                <a-col :span="3">
                  <a-form-item>
                    <a-input v-model:value="item.batch" style="width: 130px;" :disabled="disabled" />
                  </a-form-item>
                </a-col>
                <a-col :span="3">
                  <a-form-item>
                    <a-date-picker valueFormat="YYYY-MM-DD" v-model:value="item.usedDate" style="max-width: 130px;"
                      :disabled="disabled" />
                  </a-form-item>
                </a-col>
                <a-col :span="3">
                  <a-form-item>
                    <a-input v-model:value="item.outNumber" style="width: 130px;" :disabled="disabled" />
                  </a-form-item>
                </a-col>
                <a-col :span="3">
                  <a-form-item>
                    <a-input v-model:value="item.outPerson" style="width: 130px;" :disabled="disabled" />
                  </a-form-item>
                </a-col>
                <a-col :span="3">
                  <a-form-item>
                    <a-date-picker valueFormat="YYYY-MM-DD" v-model:value="item.returnDate" style="max-width: 130px;"
                      :disabled="disabled" />
                  </a-form-item>
                </a-col>
                <a-col :span="3">
                  <a-form-item>
                    <a-input v-model:value="item.putNumber" style="width: 130px;" :disabled="disabled" />
                  </a-form-item>
                </a-col>
                <a-col :span="3">
                  <a-form-item>
                    <a-input v-model:value="item.putPerson" style="width: 130px;" :disabled="disabled" />
                  </a-form-item>
                </a-col>
              </a-row>
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/@/hooks/web/useMessage';
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import JSelectInput from '../../../../../components/Form/src/jeecg/components/JSelectInput.vue';
import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
import { getValueType } from '/@/utils';
import { saveOrUpdate } from '../LabChemical.api';
import { Form } from 'ant-design-vue';
import { queryUsed } from '../LabChemicalUsedDescribe.api';
import { Modal } from 'ant-design-vue';

const props = defineProps({
  formDisabled: { type: Boolean, default: false },
  formData: { type: Object, default: () => { } },
  formBpm: { type: Boolean, default: true }
});
const formRef = ref();
const useForm = Form.useForm;
const emit = defineEmits(['register', 'ok']);
const formData = reactive<Record<string, any>>({
  id: '',
  name: '',
  type: '',
  batch: '',
  purity: '',
  factory: '',
  specs: '',
  number: '',
  units: '',
  restrictedDate: '',
  certificate: '',
  properties: '',
  tag: '',
  packages: '',
  storagePlace: '',
  buyDate: '',
  status: '',
  purpose: '',
  remark: '',
  picture: '',
  inventoryNow: undefined,
  unity: '',
});
const { createMessage } = useMessage();
const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
const confirmLoading = ref<boolean>(false);
//表单验证
const validatorRules = {

  name: [{ required: true, message: '请输入标物名称!' },],
  type: [{ required: true, message: '请输入标物类别!' },],
  batch: [{ required: true, message: '请输入标物批号!' },],
  purity: [{ required: true, message: '请输入纯度/标准!' },],
  number: [{ required: true, message: '请输入入库数量!' },],
  restrictedDate: [{ required: true, message: '请输入有效期!' },],
  status: [{ required: true, message: '请输入标物状态!' },],
};
const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: true });

// 表单禁用
const disabled = computed(() => {
  if (props.formBpm === true) {
    if (props.formData.disabled === false) {
      return false;
    } else {
      return true;
    }
  }
  return props.formDisabled;
});

/**
 * 加载生产厂家和标物类别
 */
//todo:将返回的结果放入下拉列表中


const factoryOptions = ref<Array<{ factory: string }>>();
const typeOptions = ref<Array<{ type: string }>>();
const nameOptions = ref<Array<{ name: string }>>();


onMounted(async () => {
  await getFactoryOptions();
})

async function getFactoryOptions() {
  const response = await defHttp.get({ url: "/chemical/labChemical/listFactory" });
  factoryOptions.value = response.map(item => {
    return {
      value: item.factory,
      label: item.factory
    }
  });

  const type = await defHttp.get({ url: "/chemical/labChemical/listType" });
  typeOptions.value = type.map(item => {
    return {
      value: item.type,
      label: item.type
    }
  });

  const name = await defHttp.get({ url: "/chemical/labChemical/listName" });
  nameOptions.value = name.map(item => {
    return {
      value: item.name,
      label: item.name
    };
  });
}

/**
 * 新增
 */
function add() {
  edit({});
}

/**
 * 编辑/详情
 */
const chemicalUsed = ref([]);
async function edit(record) {
  nextTick(() => {
    resetFields();
    //赋值
    Object.assign(formData, record.record);
  });
  if (record.dis) {
    //record.dis为true则查询并显示子表
    const table = await queryUsed(record.record.id);
    chemicalUsed.value = table;
  }
}

/**
 * 提交数据
 */
async function submitForm() {
  // 触发表单验证
  await validate();
  confirmLoading.value = true;
  const isUpdate = ref<boolean>(false);
  //时间格式化
  let model = formData;
  if (model.id) {
    isUpdate.value = true;
  }
  //循环数据
  for (let data in model) {
    //如果该数据是数组并且是字符串类型
    if (model[data] instanceof Array) {
      let valueType = getValueType(formRef.value.getProps, data);
      //如果是字符串类型的需要变成以逗号分割的字符串
      if (valueType === 'string') {
        model[data] = model[data].join(',');
      }
    }
  }

  const restrictedDate = new Date(model.restrictedDate); // 将字符串转换为日期对象
  // 将当前日期的时间部分设置为午夜
  const now = new Date();
  now.setHours(0, 0, 0, 0);
  console.log("今日", restrictedDate >= now);
  // 验证有效期和标物状态
  if (restrictedDate >= now && model.status === '已过期') {
    confirmLoading.value = false;
    createMessage.warning('有效期与状态冲突');
    return;
  }
  if (restrictedDate < now && model.status === '正常') {
    confirmLoading.value = false;
    createMessage.warning('有效期与状态冲突');
    return;
  }
  if (restrictedDate >= now && model.status === '已报废') {
    try {
      await new Promise<void>((resolve, reject) => {
        Modal.confirm({
          title: '确认保存',
          content: '有效期与状态不符，是否确认保存？',
          onOk() {
            resolve(); // 点击确认按钮时调用 resolve()
          },
          onCancel() {
            reject('Cancelled'); // 点击取消按钮时调用 reject()
          },
        });
      });
    } catch (error) {
      confirmLoading.value = false;
      return;
    }
  }

  await saveOrUpdate(model, isUpdate.value)
    .then((res) => {
      if (res.success) {
        createMessage.success(res.message);
        emit('ok');
      } else {
        createMessage.warning(res.message);
      }
    })
    .finally(() => {
      confirmLoading.value = false;
    });
}


defineExpose({
  add,
  edit,
  submitForm,
});
</script>

<style lang="less" scoped>
.antd-modal-form {
  min-height: 500px !important;
  overflow-y: auto;
  padding: 24px 24px 24px 24px;
}

//标题:基本信息 的格式
.antd-modal-divider {
  width: 2px;
  height: 16px;
  background: #009688;
  border-radius: 0px 0px 0px 0px;
  opacity: 1;
}

.hClass {
  width: 100px;
  height: 20px;
  font-size: 14px;
  font-family: Microsoft YaHei-Regular, Microsoft YaHei;
  font-weight: 550;
  color: #009688;
  line-height: 14px;
}

.ant-form-item-label {
  width: 60px;
  height: 20px;
  font-size: 14px;
  font-family: Microsoft YaHei-Regular, Microsoft YaHei;
  font-weight: 400;
  color: #727272;
  line-height: 20px;
}

.ant-picker {
  width: 200px !important;
  height: 32px;
  border-radius: 4px 4px 4px 4px;
  opacity: 1;
  border: 1px solid #DDDDDD;
}


:deep(.ant-form-item-control-input) {
  width: 200px !important;
}

:deep(.ant-col-sm-5) {
  display: block;
  flex: 0 0 38.83333333%;
  max-width: 38.83333333%;
}
</style>
